package com.feihong.txgw.ui.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.feihong.txgw.R;
import com.feihong.txgw.adapter.HomeRecyclerAdapter;
import com.feihong.txgw.dialog.HomeDialog;
import com.feihong.txgw.inter.contract.home.IHomeContract;
import com.feihong.txgw.json.HomeJSON;
import com.feihong.txgw.message.QueryUnReadMsgNumMessage;
import com.feihong.txgw.message.RefreshMsgIconMessage;
import com.feihong.txgw.model.bean.home.HomeDialogShowModel;
import com.feihong.txgw.model.bean.user.CityInfo;
import com.feihong.txgw.tx_precenter.HomeMainPrecenter;
import com.feihong.txgw.ui.activity.HomeActivity;
import com.feihong.txgw.ui.activity.product.HotSearchActivity;
import com.feihong.txgw.ui.activity.user.LocationActivty;
import com.feihong.txgw.ui.mvp.BaseMVPCompatFragment;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.ScreenUtil;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.nineoldandroids.view.ViewHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 * 首页Fragment  Tab1
 */

public class HomeFragment extends BaseMVPCompatFragment<IHomeContract.AbHomePrecenter> implements IHomeContract.IHomeMainView, ObservableScrollViewCallbacks {


    @BindView(R.id.home_location)
    TextView homeLocation;
    @BindView(R.id.toolbar)
    View mToolbarView;
    @BindView(R.id.list_background)
    View mListBackgroundView;
    @BindView(R.id.list)
    ObservableRecyclerView mRecyclerView;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mswiperefreshlayout;
    @BindView(R.id.img_btn_message)
    ImageButton mMsgBtn;

    @BindView(R.id.home_fragment_status_layout)
    View mStatusView;
    private HomeRecyclerAdapter homeRecyclerAdapter;


    private String latitude;
    private String longitude;

    private int mParallaxImageHeight;


    public static HomeFragment newInstance(String tabName) {
        HomeFragment homeFragment = new HomeFragment();
        homeFragment.tag = tabName;
        return homeFragment;
    }

    @Override
    public void setTheme() {
        isDrakFont = false;
    }

    @Override
    public int setLayoutID() {
        return R.layout.fragment_home;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

        EventBus.getDefault().register(this);
        initView();

        bindData();
    }

    @Override
    public void onSupportVisible() {
        setSpecificTitleLayout(mStatusView);
        super.onSupportVisible();
        if (((HomeActivity) _mActivity).isHaveNewMsg) {
            mMsgBtn.setImageResource(R.mipmap.home_unread_msg_icon);
        } else {
            mMsgBtn.setImageResource(R.mipmap.home_news);
        }
    }

    @Override
    public void initView() {
        super.initView();

        mToolbarView.setBackgroundColor(ScrollUtils.getColorWithAlpha(0, getResources().getColor(R.color.appRed)));
        mParallaxImageHeight = getResources().getDimensionPixelSize(R.dimen.parallax_image_height_small);
        mRecyclerView.setScrollViewCallbacks(this);
        //设置刷新时动画的颜色，可以设置4个
        mswiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mswiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        mswiperefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mswiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPrecenter.loadHomeData();
                        mPrecenter.loadHomeUnreadMsgCount();
                    }
                }, 200);
            }
        });
        // Set padding view for ListView. This is the flexible space.
        View paddingView = new View(getActivity());
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                mParallaxImageHeight);
        paddingView.setLayoutParams(lp);

        // This is required to disable header's list selector effect
        paddingView.setClickable(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        homeRecyclerAdapter = new HomeRecyclerAdapter(getActivity(), null);
        mRecyclerView.setAdapter(homeRecyclerAdapter);
    }

    @Override
    public void bindData() {
        super.bindData();
        mPrecenter.loadHomeAllData();
    }

    @Override
    public void setHomeData(HomeJSON result) {
        try {
            if (result != null && result.getData() != null && result.getData().getData() != null && result.getData().getData().size() > 0) {
                homeRecyclerAdapter.setNewDatas(result.getData());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void showHomeRecommendMsgDialog(HomeDialogShowModel result) {
        if (result != null && result.getData() != null && result.getCode() == 200) {
            new HomeDialog(_mActivity, result.getData().getImg_url(), result.getData().getId()).show();
        }
    }

    @Override
    public void updateLocatoin(String strLocation) {
        if (!TextUtils.isEmpty(strLocation)) {
            homeLocation.setText(strLocation);
        }
    }

    @Override
    public void setHomeUnReadMsgStatus(RefreshMsgIconMessage readMsgStatus) {
        readMsgStatus.getData().setHaveNewMsg(readMsgStatus.getData().getMsg_number() > 0 ? true : false);
        EventBus.getDefault().post(readMsgStatus);
    }

    @Override
    public void loadDataComplated() {
        if (mswiperefreshlayout.isRefreshing()) {
            mswiperefreshlayout.setRefreshing(false);
        }
    }

    @Override
    public void loadDataError() {
        ToastUtils.getInstance().showShortToast(getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return HomeMainPrecenter.create();
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        int baseColor = getResources().getColor(R.color.appRed);
        float alpha = Math.min(1, (float) scrollY / mParallaxImageHeight);
        mToolbarView.setBackgroundColor(ScrollUtils.getColorWithAlpha(alpha, baseColor));
        // Translate list background
        ViewHelper.setTranslationY(mListBackgroundView, Math.max(0, -scrollY + mParallaxImageHeight));
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {

    }

    @OnClick({R.id.home_location, R.id.btn_search})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.home_location:
                startActivityForResult(new Intent(getActivity(), LocationActivty.class), 1);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.btn_search:
                Intent location = new Intent(getActivity(), HotSearchActivity.class);
                location.putExtra("Latitude", latitude);
                location.putExtra("Longitude", longitude);
                startActivity(location);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            if (data.getStringExtra("city") != null) {
                mPrecenter.loadHomeData();
                homeLocation.setText("");
                String selectAdr = data.getStringExtra("city");
                String str;
                if (!TextUtils.isEmpty(selectAdr)) {
                    if (selectAdr.length() > 4) {
                        str = selectAdr.substring(0, 4) + "..";
                    } else {
                        str = selectAdr;
                    }
                    homeLocation.setText(str);
                }
                latitude = data.getStringExtra("Latitude");
                longitude = data.getStringExtra("Longitude");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshHomeMsgIcon(RefreshMsgIconMessage refreshMsgIconMessage) {
        if (refreshMsgIconMessage.getData().isHaveNewMsg()) {
            mMsgBtn.setImageResource(R.mipmap.home_unread_msg_icon);
        } else {
            mMsgBtn.setImageResource(R.mipmap.home_news);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void queryUnReadMsgCount(QueryUnReadMsgNumMessage queryUnReadMsgNumMessage) {
        mPrecenter.loadHomeUnreadMsgCount();
    }
}
